package com.bwda.dsrs.filecenter.controller;

import com.bwda.dsrs.base.centerbase.BaseContextHandler;
import com.bwda.dsrs.base.centerbase.condition.BaseCondition;
import com.bwda.dsrs.base.centerbase.form.BaseQueryForm;
import com.bwda.dsrs.base.centerbase.request.BaseQueryRequest;
import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.filecenter.domain.exception.BusinessServiceException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.json.JsonParseException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

/**
 * @author yangjun
 * @date 2019/4/18
 */
public class BaseController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 成功的Status Code.
     */
    private static final int RESCODE_OK = 200;
    /**
     * 失败的Status Code.
     */
    private static final int RESCODE_FAIL = 201;
    /**
     * 需要登录
     */
    private static final int RESCODE_NOT_LOGINED = 202;

    /**
     * 业务异常控制
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessServiceException.class)
    public
    @ResponseBody
    ResponseEntity businessServiceExceptionHandler(BusinessServiceException e) {
        logger.warn(e.getLocalizedMessage());
        return this.getFailResult(e.getErrCode(), e.getMessage());
    }

    /**
     * 运行期异常控制
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public
    @ResponseBody
    ResponseEntity runtimeExceptionHandler(RuntimeException e) {
        logger.error("发生系统异常", e);
        return this.getFailResult("系统异常，请和管理员联系！");
    }

    /**
     * 获取IP地址.
     *请注意，此方法获取的ip很肤浅，不一定是真实的，需要完善
     * @return
     */
    protected String getRequestIp() {
        HttpServletRequest request = requestContext();
        return request.getRemoteAddr();
//        return IPUtil.getIp(request);
    }
    /**
     * 获取请求作用域.
     * @return
     */
    protected HttpServletRequest requestContext() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
    public BaseController() {
    }

    @ExceptionHandler({BindException.class})
    public ResponseEntity bindExceptionHandler(BindException e) {
        this.logger.warn(e.getLocalizedMessage());
        return this.getFailResult(e.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseEntity methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        this.logger.warn(e.getLocalizedMessage());
        return this.getFailResult(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler({Exception.class})
    public ResponseEntity exceptionHandler(Exception e) {
        if (e instanceof JsonParseException) {
            this.logger.warn("请求体json转化出错", e);
            return this.getFailResult("请求体json转化出错");
        } else if (e instanceof HttpMediaTypeNotSupportedException) {
            this.logger.warn("http媒体类型不支持异常", e);
            return this.getFailResult("http媒体类型不支持异常:" + e.getMessage());
        } else if (e instanceof MissingServletRequestParameterException) {
            this.logger.warn("缺少参数", e.getLocalizedMessage());
            return this.getFailResult("缺少参数:" + e.getMessage());
        } else {
            this.logger.error("发生异常", e);
            return this.getFailResult("请求出错");
        }
    }

    protected <T> ResponseEntity<T> getSuccessResult(T obj) {
        return new ResponseEntity("ok", 200, "操作成功", obj);
    }

    protected ResponseEntity getSuccessResult(String msg) {
        return new ResponseEntity("ok", 200, msg, Collections.EMPTY_MAP);
    }

    protected <T> ResponseEntity<T> getSuccessResult(String msg, T obj) {
        return new ResponseEntity("ok", 200, msg, obj);
    }

    protected ResponseEntity getSuccessResult() {
        return this.getSuccessResult("操作成功");
    }

    protected ResponseEntity getFailResult(String msg) {
        return this.getFailResult(201, msg);
    }

    protected ResponseEntity getFailResult(int errCode, String msg) {
        return new ResponseEntity("fail", errCode, msg, null);
    }

    protected <T> CentreListResponse<T> getListResponse(List<T> dataList) {
        return new CentreListResponse(dataList);
    }

    protected <T> CentreCutPageResponse<T> getPageResponse(BaseQueryRequest queryRequest, Integer totalCount, List<T> dataList) {
        return new CentreCutPageResponse(queryRequest.getPageNum(), queryRequest.getPageSize(), totalCount, dataList);
    }

    protected <T> CentreCutPageResponse<T> getPageResponse(BaseCondition condition, Integer totalCount, List<T> dataList) {
        return new CentreCutPageResponse(condition.getPageNum(), condition.getPageSize(), totalCount, dataList);
    }

    protected <T> CentreCutPageResponse<T> getPageResponse(BaseQueryForm form, Integer totalCount, List<T> dataList) {
        return new CentreCutPageResponse(form.getPageNum(), form.getPageSize(), totalCount, dataList);
    }

    protected <T> CentreCutPageResponse<T> getPageResponse(int pageNum, int pageSize, Integer totalCount, List<T> dataList) {
        return new CentreCutPageResponse(pageNum, pageSize, totalCount, dataList);
    }

    public String getUserCode() throws BusinessServiceException {
        if (StringUtils.isEmpty(BaseContextHandler.getUserCode())) {
            throw new BusinessServiceException("获取用户失败，请稍后再试");
        }
        return BaseContextHandler.getUserCode();
    }

//    /**
//     * 获取审批人code
//     *
//     * @param request
//     * @return
//     * @throws BusinessServiceException
//     */
//    public String getAuditUserCode() throws BusinessServiceException {
//        String auditUsercode = "sysadmin";
//        if (!StringUtils.isEmpty(BaseContextHandler.getOrgAdminCode())) {
//            auditUsercode = BaseContextHandler.getOrgAdminCode();
//        }
//        //审批人，组织管理员，cod
//        return auditUsercode;
//    }
}

